import React, { useState, useContext, useEffect } from "react";
import {
  View,
  Text,
  StyleSheet,
  Modal,
  TextInput,
  ScrollView,
  TouchableOpacity,
  TouchableWithoutFeedback,
  ActivityIndicator,
  Alert,
} from "react-native";
import userQuesContext from "../../../context/questionnaire/UserQuesContext";
import MyQuesContext from "../../../context/questionnaire/MyQuesContext";
import { Feather } from "@expo/vector-icons";
import { AntDesign } from "@expo/vector-icons";
import LoadingBar from "../../../components/InterView/LoadingBar";

const Loading = ({ text }) => {
  return (
    <View style={styles.alterView}>
      <ActivityIndicator animating={true} size={"large"} color="#bbb" />
      <Text style={{ color: "#aaa", marginTop: 10 }}>{text}</Text>
    </View>
  );
};

const Error = () => {
  return (
    <View style={styles.alterView}>
      <Text style={{ color: "#ccc", marginTop: 10 }}>出错了...</Text>
    </View>
  );
};

const QuesOptions = ({ navigation }) => {
  const {
    myQuesLoading,
    MyQuesData,
    postMyQues,
    exportExcel,
    deleteMyQues,
    getMyQues,
    pageLen,
  } = useContext(MyQuesContext);
  const { updateQues, newQues } = useContext(userQuesContext);

  // 选择的问卷
  const [quesSelectedArr, setQuesSelected] = useState(-1);

  const [pageInputVisible, setPageInputVisible] = useState(false);
  const [page, setPage] = useState(1);

  useEffect(() => {
    getMyQues(1);
    setPage(1);
  }, []);

  React.useLayoutEffect(() => {
    navigation.setOptions({
      headerRight: () => (
        <View style={{ flexDirection: "row" }}>
          <TouchableOpacity
            onPress={() => {
              console.log("刷新");
              getMyQues(1);
              setPage(1);
            }}
          >
            <Feather name="refresh-cw" size={20} color="#fff" />
          </TouchableOpacity>
        </View>
      ),
    });
  }, [navigation]);

  // useEffect(() => {
  //   let t_Arr = [];
  //   for (let i = 0; i < MyQuesData.length; i++) {
  //     t_Arr.push(false);
  //   }
  //   setQuesSelected([...t_Arr]);
  // }, [MyQuesData]);

  const selectQues = (index) => {
    if (quesSelectedArr == index) {
      setQuesSelected(-1);
    } else {
      setQuesSelected(index);
    }
  };

  // 计数（已保存或已驳回的问卷）
  const [showNum, setShowNum] = useState(0);
  // 是否正在上传问卷
  const [isUpdating, setIsUpdating] = useState(false);
  const [isExporting, setIsExporting] = useState(false);

  // const handleSetNum = (type) => {
  //   if (type == 1) {
  //     setShowNum(showNum + 1);
  //   } else {
  //     setShowNum(showNum - 1);
  //   }
  // };
  const [isDeleting, setIsDeleting] = useState(false);

  return (
    <View style={styles.container}>
      <LoadingBar visible={myQuesLoading == "ing"} />

      <View style={{ flexDirection: "column", height: "100%" }}>
        <View style={{ flex: 15, marginTop: 10 }}>
          <View style={{ flexDirection: "row" }}>
            <View style={{ flexDirection: "row", marginRight: 20 }}>
              <View
                style={{
                  backgroundColor: "#ddd",
                  width: 12,
                  height: 12,
                  marginTop: 4,
                  marginLeft: 22,
                  marginRight: 5,
                  borderRadius: 6,
                }}
              ></View>
              <Text>未提交</Text>
            </View>
            <View style={{ flexDirection: "row", marginRight: 20 }}>
              <View
                style={{
                  backgroundColor: "#F47C68",
                  width: 12,
                  height: 12,
                  marginTop: 4,
                  marginLeft: 20,
                  marginRight: 5,
                  borderRadius: 6,
                }}
              ></View>
              <Text>已驳回</Text>
            </View>
          </View>
          <ScrollView>
            {myQuesLoading == "end" ? (
              <View>
                {MyQuesData.map((MyQues, quesIndex) => {
                  // console.log("给我显示问卷---", MyQuesData);
                  if (MyQues.state == 0 || MyQues.state == 3) {
                    // handleSetNum(1);
                    return (
                      <View key={quesIndex} style={styles.quesStyle}>
                        <View
                          style={{
                            flexDirection: "row",
                            marginTop: 10,
                            marginBottom: 5,
                            marginLeft: 12,
                            marginRoght: 12,
                          }}
                        >
                          <View style={{ flex: 1 }}>
                            <TouchableOpacity
                              onPress={() => {
                                selectQues(quesIndex);
                              }}
                            >
                              <View
                                style={
                                  quesSelectedArr == quesIndex
                                    ? styles.selectedView
                                    : styles.selectView
                                }
                              ></View>
                            </TouchableOpacity>
                          </View>
                          <TouchableOpacity
                            style={{ flex: 13 }}
                            onPress={() => {
                              updateQues(MyQues);
                              navigation.navigate("填写问卷", {
                                quesIndex: quesIndex,
                                isEdit: true,
                                isAdd: false,
                                btnType: 1,
                              });
                            }}
                          >
                            <View
                              style={{
                                flexDirection: "row",
                                justifyContent: "space-between",
                              }}
                            >
                              <Text
                                style={{
                                  fontSize: 17,
                                  fontWeight: "bold",
                                  marginLeft: 5,
                                }}
                              >
                                {MyQues.title}
                              </Text>
                              <View
                                style={{
                                  backgroundColor:
                                    MyQues.state == 0 ? "#ddd" : "#F47C68",
                                  width: 12,
                                  height: 12,
                                  marginRight: 10,
                                  borderRadius: 6,
                                }}
                              ></View>
                            </View>
                          </TouchableOpacity>
                        </View>
                        <View
                          style={{
                            flexDirection: "row",
                            marginTop: 6,
                            marginBottom: 10,
                          }}
                        >
                          <TouchableOpacity
                            style={{
                              flex: 1,
                              alignItems: "center",
                              borderRightWidth: 1,
                              borderRightColor: "#eee",
                            }}
                            onPress={() => {
                              navigation.navigate("添加入户资料", {
                                myQuesIndex: quesIndex,
                              });
                            }}
                          >
                            <Text style={{ color: "#41C3EE" }}>
                              添加入户资料
                            </Text>
                          </TouchableOpacity>
                          <TouchableOpacity
                            style={{ flex: 1, alignItems: "center" }}
                            onPress={() => {
                              navigation.navigate("问题清单", {
                                myQuesIndex: quesIndex,
                                flag: "edit",
                                showProData: MyQues.userproblem,
                              });
                            }}
                          >
                            <Text style={{ color: "#41C3EE" }}>
                              添加问题清单
                            </Text>
                          </TouchableOpacity>
                        </View>
                      </View>
                    );
                  }
                })}
              </View>
            ) : null}
            {myQuesLoading == "end" && MyQuesData.length == 0 ? (
              <View
                style={{
                  alignItems: "center",
                  marginTop: 20,
                }}
              >
                <Text style={{ color: "#ccc" }}>
                  暂无已保存的问卷，请先填写问卷
                </Text>
              </View>
            ) : null}
          </ScrollView>
        </View>
        <View
          style={{
            flex: 1.6,
            flexDirection: "row",
            alignItems: "center",
            justifyContent: "center",
          }}
        >
          <View
            style={{ flexDirection: "row", marginBottom: 8, marginLeft: 5 }}
          >
            <TouchableOpacity
              onPress={() => {
                if (page > 1) {
                  getMyQues(page - 1);
                  setPage(page - 1);
                } else {
                  Alert.alert("当前为第一页");
                }
              }}
            >
              <AntDesign name="left" size={24} color="black" />
            </TouchableOpacity>
            <TouchableOpacity
              onPress={() => {
                setPageInputVisible(true);
              }}
            >
              <Text style={{ marginTop: 2, marginLeft: 2, marginRight: 2 }}>
                {page + " / " + Math.ceil(pageLen / 30)}
              </Text>
            </TouchableOpacity>
            <TouchableOpacity
              onPress={() => {
                if (page < Math.ceil(pageLen / 20)) {
                  getMyQues(page + 1);
                  setPage(page + 1);
                } else {
                  Alert.alert("当前为最后一页");
                }
              }}
            >
              <AntDesign name="right" size={24} color="black" />
            </TouchableOpacity>
          </View>
          <TouchableOpacity
            style={styles.optionBtn}
            onPress={() => {
              // setIsVisible(true);
              newQues(1);
              navigation.navigate("填写问卷", {
                quesIndex: 0,
                isEdit: true,
                isAdd: true,
                btnType: 1,
              });
            }}
          >
            <Text>添加问卷</Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={styles.optionBtn}
            onPress={async () => {
              // setIsVisible(true);
              setIsDeleting(true);
              await deleteMyQues(quesSelectedArr);
              setIsDeleting(false);
              setQuesSelected(-1);
            }}
          >
            <Text>删除问卷</Text>
          </TouchableOpacity>
          {/* <TouchableOpacity
              style={styles.optionBtn}
              onPress={async () => {
                if (quesSelectedArr.length == 0) {
                  Alert.alert("暂无已保存的问卷");
                } else {
                  let flag = quesSelectedArr[0];
                  for (let i = 0; i < quesSelectedArr.length; i++) {
                    flag = flag || quesSelectedArr[i];
                  }
                  if (flag) {
                    setIsExporting(true);
                    await exportExcel(quesSelectedArr, "我的问卷");
                    setIsExporting(false);
                    setQuesSelected((preArr) => {
                      return preArr.map((item, index) => {
                        return false;
                      });
                    });
                    setIsExporting(false);
                  } else {
                    Alert.alert("请先选择需要导出Excel的问卷");
                  }
                }
              }}
            >
              <Text>导出Excel</Text>
            </TouchableOpacity> */}
          {/* <TouchableOpacity
              style={styles.optionBtn}
              onPress={async () => {
                if (quesSelectedArr.length == 0) {
                  Alert.alert("暂无已保存的问卷");
                } else {
                  let flag = quesSelectedArr[0];
                  for (let i = 0; i < quesSelectedArr.length; i++) {
                    flag = flag || quesSelectedArr[i];
                  }
                  if (flag) {
                    setIsUpdating(true);
                    let isSuccess = true;
                    await postMyQues(quesSelectedArr, (value) => {
                      isSuccess = value;
                    });
                    setQuesSelected((preArr) => {
                      return preArr.map((item, index) => {
                        return false;
                      });
                    });
                    setIsUpdating(false);
                    if (isSuccess) {
                      Alert.alert("上传问卷成功");
                      // handleSetNum(2);
                    } else {
                      Alert.alert("上传问卷失败");
                    }
                    // setShowNum(showNum - 1);
                  } else {
                    Alert.alert("请先选择需要上传的问卷");
                  }
                }
              }}
            >
              <Text>上传问卷</Text>
            </TouchableOpacity> */}
        </View>
      </View>

      {myQuesLoading == "error" ? <Error></Error> : null}
      {/* 输入页码 */}
      <Modal animationType="fade" transparent={true} visible={pageInputVisible}>
        <View style={styles.ModalBackground}></View>
        <TouchableWithoutFeedback
          onPress={() => {
            setPageInputVisible(false);
          }}
        >
          <View style={styles.ModalTop}></View>
        </TouchableWithoutFeedback>
        <View
          style={{
            // flex: 1,
            backgroundColor: "#fff",
            flexDirection: "row",
            padding: 10,
            height: 60,
          }}
        >
          <TextInput
            style={styles.inputBox}
            multiline={true}
            // maxLength={500}
            // value={page.toString()}
            placeholder={"输入页码"}
            // editable={isEdit}
            onChangeText={(text) => {
              setPage(Number(text));
            }}
          ></TextInput>
          <TouchableOpacity
            style={styles.replyBtn}
            disabled={page < 1 || page > Math.ceil(pageLen / 30) ? true : false}
            onPress={async () => {
              getMyQues(page);
              setPageInputVisible(false);
            }}
          >
            <Text>查找</Text>
          </TouchableOpacity>
        </View>
      </Modal>
      <Modal animationType="fade" transparent={true} visible={isUpdating}>
        <Loading text="上传中"></Loading>
      </Modal>
      <Modal animationType="fade" transparent={true} visible={isExporting}>
        <Loading text="处理中"></Loading>
      </Modal>
      <Modal animationType="fade" transparent={true} visible={isDeleting}>
        <Loading text="删除中"></Loading>
      </Modal>
    </View>
  );
};

var styles = StyleSheet.create({
  container: {
    // marginTop: Platform.OS === "android" ? StatusBar.currentHeight : 0,
    height: "100%",
    backgroundColor: "white",
  },
  ModalBackground: {
    backgroundColor: "#727272",
    opacity: 0.3,
    zIndex: 0,
    position: "absolute",
    width: "100%",
    height: "100%",
  },
  ModalStyle: {
    borderTopLeftRadius: 10,
    borderTopRightRadius: 10,
    backgroundColor: "#ffffff",
    zIndex: 1,
    position: "relative",
  },
  ModalTop: {
    flex: 1,
  },
  modalOption: {
    // backgroundColor: "yellow",
    width: "100%",
    padding: 15,
    borderBottomWidth: 0.5,
    borderBottomColor: "#e6e6e6",
  },
  modalText: {
    alignSelf: "center",
    fontSize: 16,
    color: "#201D1D",
  },
  optionBtn: {
    height: 40,
    width: "30%",
    // marginTop: 0,
    marginLeft: 7,
    marginRight: 7,
    alignItems: "center",
    justifyContent: "center",
    backgroundColor: "#41C3EE",
    elevation: 4, //设置阴影角度，通过这个设置有无阴影
    shadowOffset: {
      // 设置阴影偏移量
      width: 0,
      height: 0,
    },
    shadowRadius: 4, // 设置阴影模糊半径
    shadowOpacity: 0.5, // 设置阴影的不透明度
    shadowColor: "gray", // 设置阴影色
  },
  quesStyle: {
    marginLeft: 20,
    marginRight: 20,
    marginTop: 10,
    marginBottom: 10,
    borderRadius: 5,
    // borderWidth: 1,
    // borderColor: "#eee",
    backgroundColor: "#fff",
    elevation: 4, //设置阴影角度，通过这个设置有无阴影
    shadowOffset: {
      // 设置阴影偏移量
      width: 0,
      height: 4,
    },
    shadowRadius: 4, // 设置阴影模糊半径
    shadowOpacity: 0.1, // 设置阴影的不透明度
    shadowColor: "gray", // 设置阴影色
  },
  selectView: {
    width: 14,
    height: 14,
    borderRadius: 7,
    borderWidth: 1,
    borderColor: "#ccc",
    marginTop: 4,
  },
  selectedView: {
    width: 14,
    height: 14,
    borderRadius: 7,
    borderWidth: 1,
    borderColor: "#eee",
    backgroundColor: "#41C3EE",
    marginTop: 4,
  },
  alterView: {
    height: "100%",
    alignItems: "center",
    justifyContent: "center",
  },
  ModalBackground: {
    backgroundColor: "#727272",
    opacity: 0.3,
    zIndex: 0,
    position: "absolute",
    width: "100%",
    height: "100%",
  },
  ModalStyle: {
    borderTopLeftRadius: 10,
    borderTopRightRadius: 10,
    backgroundColor: "#ffffff",
    zIndex: 1,
    position: "relative",
  },
  ModalTop: {
    flex: 1,
  },
  modalOption: {
    // backgroundColor: "yellow",
    width: "100%",
    padding: 15,
    borderBottomWidth: 0.5,
    borderBottomColor: "#e6e6e6",
  },
  inputBox: {
    height: 40,
    // marginTop: 6,
    borderColor: "#ddd",
    borderWidth: 1,
    // height: 100,
    borderRadius: 3,
    // padding: 10,
    // paddingTop: 10,
    // paddingBottom: 10,
    marginLeft: 5,
    marginRight: 5,
    width: "76%",
  },
  replyBtn: {
    margin: 1,
    width: "20%",
    backgroundColor: "#41C3EE",
    borderRadius: 3,
    alignItems: "center",
    justifyContent: "center",
  },
});

export default QuesOptions;
